package com.hfjyz.base.converter;

import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableCell;
import org.apache.poi.hwpf.usermodel.TableIterator;
import org.apache.poi.hwpf.usermodel.TableRow;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import com.hfjyz.base.bean.BaseBean;

public abstract class Converter<T extends BaseBean> {
    public abstract String getFilePath();

    public abstract T readFromTable();

    public Table getTable() throws IOException {
        FileInputStream in = null;
        try {
            in = new FileInputStream(getFilePath());
            POIFSFileSystem pfs = new POIFSFileSystem(in);
            HWPFDocument hwpf = new HWPFDocument(pfs);
            // 得到文档的读取范围
            Range range = hwpf.getRange();
            TableIterator it = new TableIterator(range);
            if (it.hasNext()) {
                return it.next();
            }
            return null;
        } finally {
            in.close();
        }
    }

    public String readFromTable(Table table, int row, int column) {
        TableRow tr = table.getRow(row);
        TableCell td = tr.getCell(column);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < td.numParagraphs(); i++) {
            if (i != 0) {
                sb.append("\r\n");
            }
            Paragraph para = td.getParagraph(i);
            sb.append(para.text().trim());
        }
        return sb.toString();
    }
}
